package com.gk.javaservice.util.meeting;

import javax.net.ssl.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;

public class FileChecker {

    // 忽略SSL证书验证
    private static void trustAllCertificates() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() { return null; }
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {}
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {}
                }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // 创建并设置 HostnameVerifier
        HostnameVerifier allHostsValid = (hostname, session) -> true;
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    }

    public static boolean checkFileExists(String fileUrl) {
        try {
            trustAllCertificates(); // 设置信任所有证书

            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("HEAD");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            int responseCode = connection.getResponseCode();
            return responseCode == HttpURLConnection.HTTP_OK;
        } catch (Exception e) {
            System.out.println("检查文件时发生异常：" + e.getMessage());
            return false;
        }
    }

    public static void main(String[] args) {
        String fileUrl = "https://192.168.10.38/record/123123123/123123123_Administrator_1742371826166.mp4";
        if (checkFileExists(fileUrl)) {
            System.out.println("文件存在");
        } else {
            System.out.println("文件不存在或无法访问");
        }
    }
}
